﻿package com.cilico.single.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.components.AtomParser;
import com.cilico.single.components.WaitDialog;
import com.cilico.single.utils.HttpManager;
import com.cilico.single.utils.HttpManager.NoGatewayException;
import com.cilico.single.utils.PackageManagerAndroid;
import com.cilico.single.utils.Utils;

/**
 * 管理用户状态 cookie session 密钥等信息
 * 
 * @author lv.xiangan
 *
 */
public class UserManager {
	private Mid mid_;
	private PackageManagerAndroid pm_;
	private boolean loggedIn_;
	public String loginStatus_;
	public String name_;
	public String loginTimes_;
	public String lastLogin_;
	public String checkInfo_;
	public Vector<String> menuV_;
	public String downloadCode_;
	public int userid_;
	public String channelId_;
	public boolean isShowLaunchS_;// 当用户选择显示launcher screen时为真
	public static final int UM_SUCCESS = 0;
	public static final int UM_SIGNUP = 1;
	public static final int UM_WRONGPIN = 2;
	public static final int UM_SOFTWARE_UPDATE = 3;
	public static final int UM_ERROR_INFO = 4;
	public static final int UM_SOFTWARE_UPDATE_OPTION = 5;
	/**apk在服务器上的路径*/
	public String apk_host_path = "";
	/**服务器传来的版本号*/
	public String versionNum_;
	/**服务器上的APK名字*/
	private String apkName_ = "";

	public UserManager(Mid mid, HttpManager hm, PackageManagerAndroid pm, Activity activity) {
		pm_ = pm;
		mid_ = mid;
		loggedIn_ = false;
		isShowLaunchS_ = true;
		channelId_ = null;
	}

	public boolean userLoggedIn() {
		return loggedIn_;
	}

	/**
	 * 初始化。从RMS读入初始化信息
	 */
	public void loadState() {
		try {
			channelId_ = pm_.readString(pm_.permDB_, PackageManagerAndroid.RMSKEY_CHANNEL_REALID);
		} catch (Exception ex1) {
			Utils.printOutToConsole("UserManager-loadState-ex1:" + ex1.toString());
			channelId_ = null;
		}
		try {
			String str = pm_.readString(pm_.permDB_, PackageManagerAndroid.RMSKEY_USERID);
			if (str == null)
				userid_ = -1;
			else
				userid_ = Integer.parseInt(str);
			Utils.printOutToConsole("Userid " + userid_);
		} catch (Exception ex3) {
			Utils.printOutToConsole("UserManager-loadState-ex3:" + ex3.toString());
			userid_ = -1;
		}
		if (userid_ == -1) {
			loggedIn_ = false;
		}
		try {
			String str = pm_.readString(pm_.permDB_, PackageManagerAndroid.RMSKEY_LAUNCH_SCREEN);
			if (str != null)
				isShowLaunchS_ = str.equals("true");

			Utils.printOutToConsole("isShowLaunchS " + str);
		} catch (Exception ex) {
			isShowLaunchS_ = true;
		}
	}

	/**
	 * Only reset cookie-related login credentials. LoginKey is tied to user's account when the account was created and
	 * should only become obsolete when we switch server.
	 */
	public void resetLoginData() {
		loggedIn_ = false;
	}

	/**
	 * Reset cached login keys to prompt for a full login.
	 */
	public void resetLoginAndKeys() {
		resetLoginData();
		isShowLaunchS_ = true;
		channelId_ = null;
	}

	/**
	 *  如果客户端注册界面由服务端执行，则用该方法登录
	 * @param host
	 * @param body
	 * @param isSignIn
	 * @param bv
	 * @param task
	 * @return
	 * @throws Exception
	 */
	public int userLogin(final String host, final String body, boolean isSignIn, final BaseView bv, WaitDialog.Task task) throws Exception {
		int retCode = UM_SUCCESS;
		String reply = "";
		try {
			reply = (String) BaseView.mid_.hm_.sendPostRequest(host, body, task, null, null);
		} catch (Exception ex) {
			if (ex instanceof NoGatewayException) {
				//无论前一次使用什么方式联网，都换一种方式再次尝试连接
				HttpManager.connectType_ = 1 - HttpManager.connectType_;
				reply = (String) BaseView.mid_.hm_.sendPostRequest(host, body, task, null, null);
			} else {
				throw ex;
			}
		}

		if (reply == null)
			throw new NullPointerException("无法获取服务器的登录响应。");
		if (reply.indexOf("<error") != -1) {
			String error = Utils.getXMLResponseAttribute(reply, "string=\"", 0, Utils.MATCH);
			if (task != null)
				task.setErrMsg(error);
			return UM_ERROR_INFO;
		}
        Utils.printOutToConsole("parsexml = " + reply);
		if (reply.indexOf("<error") != -1) {
			String error = Utils.getXMLResponseAttribute(reply, "string=\"", 0, Utils.MATCH);
			if (task != null)
				task.setErrMsg(error);
			return UM_ERROR_INFO;
		}

		if (null == mid_.parser_) {
			mid_.parser_ = new AtomParser(BaseView.mid_);
		}

		if (isSignIn) {
			// 该判断条件为防止tms无用户信息的情况出现
			// 前提为服务端仍会返回注册界面给客户端
			if (reply.indexOf("<phone_identity ") < 0) {
				isSignIn = false;
				ConfigManager.TMS_CLEARED_USERINFO = true;
			}
		}
		Utils.printOutToConsole("reply====="+reply);
		if (isSignIn) {//登录
			if (reply.indexOf("<phone_identity ") < 0){
				BaseView.mid_.parserLoginMessage(bv, reply);
			} else{
				mid_.parser_.setLoginResultProperty(AtomParser.parseLoginResult_, this, mid_.channelRepo_, null);
				android.util.Xml.parse(reply, mid_.parser_);	
			}
		} else {
			if (reply.indexOf("<phone_identity ") > 0){
				mid_.parser_.setLoginResultProperty(AtomParser.parseLoginResult_, this, mid_.channelRepo_, null);
				android.util.Xml.parse(reply, mid_.parser_);
				mid_.istoMain_ =true;
			} else
			BaseView.mid_.parserLoginMessage(bv, reply);//注册
		}

		mid_.channelRepo_.downloadChannelListSuccess();
		int checkSoftawre = checkSoftwareUpdate();
		if (checkSoftawre == 2)
			retCode = UM_SOFTWARE_UPDATE;
		else if (checkSoftawre == 1)
			retCode = UM_SOFTWARE_UPDATE_OPTION;
		loggedIn_ = true;
		return retCode;

	}

	/**
	 *  显示登录界面
	 * @param activity
	 * @param reply
	 */
	final void showLoginView(final BaseView activity, final String reply) {
		try {
			boolean isToMainView = false;
			boolean isToDetailView = false;
	        Utils.printOutToConsole("parsexml = " + reply);
			if (reply.indexOf("<phone_identity ") > -1) {
				// 应跳转到九宫格页面
				isToMainView = true;
				mid_.parser_.setLoginResultProperty(AtomParser.parseLoginResult_, mid_.um_, mid_.channelRepo_, null);
				android.util.Xml.parse(reply, mid_.parser_);
				mid_.channelRepo_.downloadChannelListSuccess();
			} else if (reply.indexOf("<detailpage") > -1) {
				isToDetailView = true;
			} else {
				// 仍处于登录页面
				mid_.parserLoginMessage(activity, reply);
			}
			if (isToMainView) {
				BaseView.mid_.poiRepo_.popActionPoi();
				mid_.handleLoginSuccess(activity);
			} else if (isToDetailView) {
				// 手动初始化九宫格内容
				BaseView.mid_.poiRepo_.popActionPoi();
				if (null == mid_.parser_) {
					mid_.parser_ = new AtomParser(BaseView.mid_);
				}
				mid_.parser_.setLoginResultProperty(AtomParser.parseLoginResult_, this, mid_.channelRepo_, null);
				String initContent = Utils.getStringFormAsset(activity, "xmlview/mainview.xml");
				android.util.Xml.parse(initContent, mid_.parser_);
				mid_.channelRepo_.downloadChannelListSuccess();
				
				// 清空资源
				try {
					// 直接清空隐藏域和本地栈集合
					activity.delContentStack();
					if (activity.tabBar_ != null)
						activity.removeAll();
					mid_.parser_.dispose();
					mid_.parser_ = null;
					mid_.parser_ = new AtomParser(mid_);
					activity.dispose();
					mid_.removeDisplayable();
					// 清栈
					if (mid_.poiRepo_ != null) {
						mid_.poiRepo_.removeAllActionPoi();
					}
				} catch (Exception e) {
					Utils.printOutToConsole("清空资源时的警告，可以忽略：" + e.getMessage());
				}
				
				String chid = "cilico_youhuixinxi_visitor";
				mid_.channelRepo_.setCurrentChannelID(chid);
				
				Channel mainChannel = mid_.channelRepo_.getChannel(chid); // 获取当前频道
				mid_.channelEntity_.gotoDetailViewFromClientHello(null, activity, Mid.DETAIL_VIEW, mainChannel.id(), mainChannel.title());
			} else {
				if (!activity.isFinishing()) {
					Intent intent = new Intent();
					intent.setClass(activity, LoginView.class);
					activity.startActivity(intent);
					WaitDialog.Task.cancelProgressBar(activity);
					activity.finish();
				}
			}
		} catch (Exception e) {
			Utils.printException(e);
		}
	}

	/**
	 * @param activity
	 * @param body
	 */
	public final void processGetUi(final BaseView activity, final String body) {
		mid_.waitDialog_.addBgTask(new WaitDialog.Task(0) {
			boolean isToMainView = false;
			@Override
			public void run(WaitDialog dlg) throws Exception {
				String reply = null;
				try {
					reply = (String) mid_.hm_.sendPostRequest(ConfigManager.SERVER_URI_LOGIN, body, this, null, null);
				} catch (Exception ex) {
					if (ex instanceof NoGatewayException) {
						//无论前一次使用什么方式联网，都换一种方式再次尝试连接
						HttpManager.connectType_ = 1 - HttpManager.connectType_;
						reply = (String) mid_.hm_.sendPostRequest(ConfigManager.SERVER_URI_LOGIN, body, this, null, null);
					} else {
						throw ex;
					}
				}

				if (reply.indexOf("<phone_identity ") > -1) {
					// means it should go into Main View.
					isToMainView = true;
					mid_.parser_.setLoginResultProperty(AtomParser.parseLoginResult_, mid_.um_, mid_.channelRepo_, null);
					android.util.Xml.parse(reply, mid_.parser_);
					mid_.channelRepo_.downloadChannelListSuccess();
				} else {
					// 仍处于登陆页
					mid_.parserLoginMessage(activity, reply);
				}
			}

			public void onSuccess(WaitDialog dlg) {
				if (isToMainView) {
					mid_.handleLoginSuccess(activity);
				} else {
					Intent intent = new Intent();
					intent.setClass(activity, LoginView.class);
					activity.startActivity(intent);
					WaitDialog.Task.cancelProgressBar(activity);
					activity.finish();
				}
			}

			public void onFailure(WaitDialog dlg) {
				if (isToMainView) {
					mid_.handleLoginFailureAgain(activity);
				} else {
					mid_.alert(activity, getErrMsg(), false);
				}
			}
		});
	}


	/**
	 * 检查是否版本更新
	 * Return true if there is a newer version ready for download.
	 */
	private int checkSoftwareUpdate() {
		if (mid_.updateMode_ == true) {
			// If we don't receive version number from server, assume we are up-to-date.
			if (versionNum_ == null || versionNum_.length() == 0) {
				versionNum_ = "0.0.0";
				return 0;
			}
			// NOTE: if we need a version update, continue to process and read
			// all the rest of information, because we need to allow user to continue
			// operation with the current version if she chooses so.
			int newNum = versionNumToInt(versionNum_);
			// int oldNum = versionNumToInt(BaseView.mid_.midletVersion_);
			int oldNum = 1;
			if (newNum > 0 && oldNum > 0 && newNum > oldNum) {
				if (newNum - oldNum < 100) {
					return 1;
				} else {
					return 2;
				}
			}
		}
		return 0;
	}
	
	/**
	 * 与服务器建立连接
	 * @param activity
	 * @param body
	 */
	public final void clientHello(final BaseView bv) throws Exception {
		//重新登录时将九宫格的当前页置0
		MainView.currentPageIndex_ = 0;
	    fullClientHello(bv);
	}
	
	/**
	 * 请求后台。握手完整流程
	 * @param activity
	 * @param body
	 */
	final void fullClientHello(final BaseView bv) throws Exception {
		mid_.waitDialog_.addBgTask(new WaitDialog.Task(0) {
			String initContent = "";

			@Override
			public void run(WaitDialog dlg) throws Exception {
				HttpManager hm = mid_.hm_;
				String uri = ConfigManager.CLIENT_HELLO;
				if (getInternetConnectType(bv)) {
					HttpManager.connectType_ = 1;
				}
				// get server hello.
				try {
					String bodyStr = null;
					initContent = (String) hm.sendPostRequest(uri, bodyStr, this, null, null);
				} catch (Exception ex) {
					if (ex instanceof NoGatewayException) {
						//无论前一次使用什么方式联网，都换一种方式再次尝试连接
						HttpManager.connectType_ = 1 - HttpManager.connectType_;
						String bodyStr =null;
						initContent = (String) hm.sendPostRequest(uri, bodyStr, this, null, null);
					} else {
						throw ex;
					}
				}
			}

			public void onSuccess(WaitDialog dlg) {
				showLoginView(bv, initContent);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(bv, getErrMsg(), false);
				super.onFailure(dlg);
			}
		});
	}

	/***
	 * 判断Network具体类型（联通、移动wap，电信wap，其他net）
	 * 当是联通、移动wap，电信wap时返回true,　其它情况返回false。当返回true时，
	 * 需要根据waphost设置代理，联通unwap、移动cmwap的waphost = "http://10.0.0.172:80";　
	 * 电信ctwap的waphost = "http://10.0.0.200:80";
	 * 有极少h手机判断可能不正确
	 **/
	public boolean getInternetConnectType(Context mContext) {
		try {
			final ConnectivityManager cManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			final NetworkInfo netInfo = cManager.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isAvailable()) {
				int netType = netInfo.getType();
				if (netType == ConnectivityManager.TYPE_MOBILE) {
					// 判断电信wap
					Uri netUri = Uri.parse("content://telephony/carriers/preferapn");
					final Cursor c = mContext.getContentResolver().query(netUri, null, null, null, null);
					try {
						if (c != null) {
							c.moveToFirst();
							final String user = c.getString(c.getColumnIndex("user"));
							if (!TextUtils.isEmpty(user)) {
								if (user.startsWith("ctwap")) {
									Utils.wapHost = "http://10.0.0.200:80";
									return true;
								}
							}
						}
					} catch (Exception ex) {
					} finally {
						c.close();
					}

					// 移动、联通：采用getExtraInfo获取接入点名字进行判断
					String netMode = netInfo.getExtraInfo();
					if (netMode != null) {
						// 通过apn名称判断是否是联通和移动wap
						netMode = netMode.toLowerCase();
						if (netMode.equals("cmwap") || netMode.equals("3gwap") || netMode.equals("uniwap")) {
							Utils.wapHost = "http://10.0.0.172:80";
							return true;
						}
					}
				}
			}
		} catch (Exception ex) {
		}
		return false;
	}
	
	
	/**
	 * @param bv
	 * @param url
	 * @param body
	 */
	final void switchUIVIew(final BaseView bv, final String url, String body) throws Exception {
		final String fBody = body;
		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			String initContent = "";

			@Override
			public void run(WaitDialog dlg) throws Exception {
				HttpManager hm = mid_.hm_;
				// get server hello.
				try {
					initContent = (String) hm.sendPostRequest(url, fBody, this, null, null);
				} catch (Exception ex) {
					if (ex instanceof NoGatewayException) {
						//无论前一次使用什么方式联网，都换一种方式再次尝试连接
						HttpManager.connectType_ = 1 - HttpManager.connectType_;
						initContent = (String) hm.sendPostRequest(url, fBody, this, null, null);
					} else {
						throw ex;
					}
				}
				if (initContent == null)
					throw new NullPointerException("无法获取服务器的登录响应。");
			}

			public void onSuccess(WaitDialog dlg) {
				BaseView.CHANGEWORKED = false;
				showLoginView(bv, initContent);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(bv, getErrMsg(), false);
				super.onFailure(dlg);
			}
		}, false);
	}


	public final int versionNumToInt(String str) {
		String versionNumber1, versionNumber2, versionNumber3;
		versionNumber1 = versionNumber2 = versionNumber3 = "0";
		int firstIndex = str.indexOf('.');
		int secondIndex = str.indexOf('.', firstIndex + 1);
		if (firstIndex != -1) {
			versionNumber1 = str.substring(0, firstIndex);
			if (secondIndex != -1) {
				versionNumber2 = str.substring(firstIndex + 1, secondIndex);
				versionNumber3 = str.substring(secondIndex + 1);
			}
		}
		return Integer.parseInt(versionNumber1) * 10000 + Integer.parseInt(versionNumber2) * 100 + Integer.parseInt(versionNumber3);
	}
	
	/**
	 * 下载APK
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2014-3-12下午2:55:27
	 * @param context
	 */
	private void downLoadApk(Context context){
    	HttpClient httpClient = new DefaultHttpClient();
		HttpGet get = new HttpGet(apk_host_path);
		HttpResponse response;
		InputStream is = null;
		FileOutputStream fileOutputStream = null;
		try {
			response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			long len = entity.getContentLength();
			if(is!=null){				
				fileOutputStream = context.openFileOutput(apkName_, Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
				byte[] buf = new byte[1024];
				int ch = -1;
				while((ch = is.read(buf)) != -1){
					fileOutputStream.write(buf, 0, ch);
				}
			}
			fileOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			/**
			 * 2012-09-25
			 * 修改部分：关闭输入流
			 */
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
    }
	
	/**
	 * 在线升级版本
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2014-3-12下午3:09:21
	 * @param context
	 */
	public void updateVersion(final Context context)
	{
		String[] ss = apk_host_path.split("/");
		apkName_ = ss[ss.length-1];
		final ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setTitle("警告");
		progressDialog.setMessage("系统正在升级中，请耐心等候....");
		progressDialog.setCancelable(false);
		progressDialog.show();
		final Handler handler = new Handler()
		{

			@Override
			public void handleMessage(Message msg)
			{
				try
				{
					switch (msg.what)
					{
					case 1:
						progressDialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_VIEW);
						File file = new File(ConfigManager.PATH_ROOT
								+ "/files/" + apkName_);
						Uri uri = Uri.fromFile(file);
						intent.setDataAndType(uri,
								"application/vnd.android.package-archive");
						context.startActivity(intent);
						break;
					default:
						break;
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}

		};
		Thread thread = new Thread()
		{

			@Override
			public void run()
			{
				downLoadApk(context);
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}

		};
		thread.start();
	}


}
